(function(win){
	var Z = win.Z,
		Bundle = Z.Bundle,
		BundleList = Z.BundleList;

	var bundle = new Bundle({'tmpl' : 'remote'});

	function remoteRequest(method, data, callback) {
		data['method'] = method;
		data['url'] = 'http://' + bundle.find('select[name="server"]').val() + '/cmsapi/mobileTool.php';
		Z.ajax({
			'url' : Z.route('Proxy', 'jsonp'),
			'type' : 'post',
			'data' : data,
			'success' : callback
		});
	}

	var callbacks = [
		function() {
			var loading = Z.loading();
			remoteRequest('getMobConf', {}, function(data) {
				bundle.find('ul.records').html(win.tmpl(bundle.find('script:eq(0)').html(), data));
				loading.close();
			});
		},
		function() {
			var loading = Z.loading();
			remoteRequest('getServers', {}, function(data) {
				var i, records = data.records, l = records.length, addresses = {};
				for(i = 0;i < l;i += 1) {
					addresses[records[i]['svid']] = [records[i]['svmobip'],records[i]['svport']];
				}
				Z.ajax({
					'url' : Z.route('proxy', 'check'),
					'data' : {'address' : addresses},
					'success' : function(status) {
						data['status'] = status;
						bundle.find('tbody:eq(0)').html(win.tmpl(bundle.find('script:eq(1)').html(), data));
						loading.close();
					}
				});
			});
		},
		function() {
			remoteRequest('getTableSchema', {'table' : bundle.find('input[name="tableName"]').val()}, function(data) {
				var i, l = data.length, trs = [];
				for(i = 0;i < l;i += 1) {
					trs.push(win.tmpl(bundle.find('script.fields').html(), data[i]));
				}
				bundle.find('tbody:eq(1)').html(trs.join(''));
			});
		},
		function() {
			remoteRequest('getOrders', {'mid' : bundle.find('input[name="mid"]').val()}, function(data) {
				console.log(data);
			});
		}
	];

	bundle.onload = function(){
		var index = 0;
		Z.tab(bundle.find('ul.tab-button a'), bundle.find('div.tab-content'), ['active'], function(i) { index = i; });
		Z.ajax({
			'url' : Z.route('server', 'records'),
			'success' : function(data) {
				Z.Form.fillSelect(bundle.find('select[name="server"]'), data.records, function(i, item) {
					return [item.url, item.name];
				});
			}
		});
		bundle.find('a.submit').click(function() {
			callbacks[index]();
			return false;
		});
	};

	BundleList.append(bundle);
})(window);